package cn.lsoft.undoner.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 *@fileName   : UtilsBean.java
 *@description: 工具类
 */
public class BeanUtil {
	
	private static final String POSSIBLE_CHARS="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	
	/**
	 * 产生一个指定长度的随机字符串
	 * @param length 字符串长度
	 * @return
	 */
	public static  String generateRandomString(int length) {
		StringBuilder sb = new StringBuilder(length);
		SecureRandom random = new SecureRandom();
		for (int i = 0; i < length; i++) {
			sb.append(POSSIBLE_CHARS.charAt(random.nextInt(POSSIBLE_CHARS.length())));
		}
		return sb.toString();
	}
	
	/** 
     * 把对象组装成MAP（不包括空数据）
     * @param sArray 对象
     * @return 转换后MAP
	 * @throws UnsupportedEncodingException 
     */
	public static Map convertObj2Map(Object bean, String inputCharset)throws IntrospectionException, IllegalAccessException, InvocationTargetException, UnsupportedEncodingException {
        Class type = bean.getClass();
        Map returnMap = new HashMap();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);

        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (int i = 0; i< propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    returnMap.put(propertyName, URLDecoder.decode(result.toString(), inputCharset));
                }
            }
        }
        return returnMap;
    }
	
	/** 
     * 除去数组中的空值和签名参数
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {

        Map<String, String> result = new HashMap<String, String>();

        if (sArray == null || sArray.size() <= 0) {
            return result;
        }

        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("signValue")
                || key.equalsIgnoreCase("signType")|| key.equalsIgnoreCase("payType")) {
                continue;
            }
            result.put(key, value);
        }

        return result;
    }
    
    
    public static final boolean isEmptyString(String s){
		if(s==null || "".equals(s.trim()))
			return true;
		return false;
	}
    
    
    /** 
     * 判断queryString的有效性
     * @param sArray 待判断的参数
     * @return 只有_input_charset字段才是有效的传参
     */
    public static final boolean isValidQueryString(String queryString){
		if(queryString==null) return false;
		String[] q = queryString.split("=");
		if (q.length != 2){
			return false;
		}
		if (!q[0].equals("inputCharset")){
			return false;
		}
		return true;
	}

    /** 
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }
    
    /** 
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后ENCODE字符串
     * @throws UnsupportedEncodingException 
     */
    public static String createEncodeLinkString(Map<String, String> params, String charact) throws UnsupportedEncodingException {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String val;
            String value;
			if((val = params.get(key)) != null){
				value = URLEncoder.encode(val, charact);
            }{
            	value = val;
            }

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }

    /*生成32位随机数*/
    public static String getUUID(){   
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");   
        return uuid;   
    }
    /*获取没有中文字符的非空普通字符串*/
	 public static String getNormolString(String beanItem){
		 if (isEmptyString(beanItem))
			 return "";
		 return beanItem;
	 }
	 
	 /*获取含有中文的非空字符串-已进行URLEncoder.encode进行GBK编码*/
	 public static String getEncodeStringA(String beanItem, String _input_charset) throws UnsupportedEncodingException{
		 if (isEmptyString(beanItem))
			 return "";
		 return URLEncoder.encode(beanItem, _input_charset);
	 }
	 
	 /*获取含有中文的非空字符串-未进行URLEncoder.encode进行GBK编码*/
	 public static String getEncodeStringB(String beanItem, String _input_charset) throws UnsupportedEncodingException{
		 if (isEmptyString(beanItem))
			 return "";
		 return URLEncoder.encode(URLEncoder.encode(beanItem, _input_charset), _input_charset);
	 }
	 
	 public static String getDecodeString(String beanItem, String charact) throws UnsupportedEncodingException{
		 if (isEmptyString(beanItem))
			 return "";
		 return URLDecoder.decode(beanItem, charact);
	 }
	 
	 /*获取当前时间*/
	 public static String getCurDate(){
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 return sdf.format(new Date());
	 }
	 
	 
	 /*获取前一天当前时间*/
	 public static String getYesterday(String curTime, String format) throws ParseException{
		Calendar cal = Calendar.getInstance(); 
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date nowDate  = sdf.parse(curTime);
		cal.setTime(nowDate);
		int day = cal.get(Calendar.DATE);  
		cal.set(Calendar.DATE, day-1);  
		String mTime = sdf.format(cal.getTime());
		return mTime;
	 }
	 
	 
	 public static String getUriValue(String key , String uri){
		 if (key == null || key.length() == 0){
			 return "";
		 }
		 if (uri == null || uri.length() == 0){
			 return "";
		 }
		 String []arrSplit=uri.split("&"); 
		 for(String strSplit:arrSplit) 
		 { 
			 String[] arrSplitEqual=null; 
			 arrSplitEqual= strSplit.split("="); 
			 //解析出键值 
			 if(arrSplitEqual.length > 1) 
			 { 
				 //正确解析 
				 if (arrSplitEqual[0].equals(key)){
					return  arrSplitEqual[1]; 
				 } 
			 } 
			 else 
			 { 
				 continue;
			 }
		 }
		 return "";
		 
	 }
	 public static void main(String[] args){
		String now = "2016-05-16 10:34:30";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date dateNow = sdf.parse(now);
			String dateOver = sdf.format(new Date(dateNow.getTime() - 30*60*1000));
			System.out.println(dateOver);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	 }
}
